package com.cqc.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqc.dao.db1.User1Mapper;
import com.cqc.dao.db2.User2Mapper;
import com.cqc.entity.User1EB;
import com.cqc.entity.User2EB;
import com.cqc.service.UserService;
import com.cqc.service.User1Service;
import com.cqc.service.User2Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    User1Mapper user1Mapper;
    @Autowired
    User2Mapper user2Mapper;


    @Override
    @Async
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
    public void migrate() {
        //从db1中读取数据，数据量不大，可以一次性读取
        List<User1EB> db1UserList = user1Mapper.selectList(null);
        for (User1EB user1EB : db1UserList) {
            User2EB user2EB = new User2EB();
            BeanUtils.copyProperties(user1EB, user2EB);
            user2Mapper.insert(user2EB);
            logger.info(user2EB.toString());
        }
    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
    public void migrate2() {
        Long total = user1Mapper.selectCount(null);
        int pageSize = 1000;
        long pageTotal = (total % pageSize) == 0 ? (total / pageSize) : (total / pageSize + 1);
        for (int i = 1; i <= pageTotal; i++) {
            Page<User1EB> page = user1Mapper.selectPage(Page.of(i, pageSize), Wrappers.lambdaQuery(User1EB.class).orderByAsc(User1EB::getId));
            List<User1EB> eb1List = page.getRecords();
            List<User2EB> eb2List = new ArrayList<>();
            for (User1EB user1EB : eb1List) {
                User2EB user2EB = new User2EB();
                BeanUtils.copyProperties(user1EB, user2EB);
                eb2List.add(user2EB);
            }
            user2Mapper.insertBatch(eb2List);
            logger.info("数据总数：{},共执行{}次，这是第{}次", total, pageTotal, i);
        }
        logger.info("数据迁移结束");
    }
}
